package com.zion.tencent_dnspod_api.service;

import cn.hutool.core.net.NetUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.impl.client.CloseableHttpClient;
import org.jsoup.Jsoup;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 获取本机IP的网络服务
 *
 * @Author ZionChen
 * @Date 2024/1/5 02:04
 * @PackageName:com.zion.dnspod_update.service
 * @ClassName: HostServiceImpl
 * @Description: TODO
 * @Version 1.0
 */
@Service
@Slf4j
public class HostServiceImpl {
    @Resource
    private CloseableHttpClient httpClient;

    /**
     * 获取本机内网IP地址
     *
     * @return 返回局域网IP地址
     */
    public String getLocalAddress() {

        String ip = NetUtil.getLocalhostStr();
        log.info("获取内网IP={}", ip);
        return ip;
    }

    /**
     * 调用网页服务，获取公网IP地址
     *
     * @return 返回公网IP地址
     */
    public String getPublicAddress() {
        String getIpHost = "http://ipv4.icanhazip.com";
        Map<String, String> headers = new HashMap<>();
        headers.put("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.1 Safari/605.1.15");
        headers.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        headers.put("Accept-Encoding", "gzip, deflate");
        try {
            String ip = Jsoup.connect(getIpHost).headers(headers).timeout(10 * 1000).postDataCharset("utf-8").get().text();

            log.info("公网ip={}", ip);
            return ip;
        } catch (IOException e) {
            log.error("访问获取公网IP返回错误，请检查报错");
            throw new RuntimeException(e);
        }

    }
}
